<template>
  <section>
    <SearchBar>
      <SearchBarItem :label="$t('mockHandler.project')">
        <a-select :placeholder="$t('operation.select')" v-model:value="searchForm.projectId" allow-clear>
          <a-select-option v-for="item in projects" :key="item.projectId">{{ item.projectName }}</a-select-option>
        </a-select>
      </SearchBarItem>
      <SearchBarItem :label="$t('mockHandler.name')">
        <a-input :placeholder="$t('operation.enter')" v-model:value="searchForm.name" allow-clear/>
      </SearchBarItem>
      <SearchBarItem :label="$t('mockHandler.httpMethod')">
        <a-select :placeholder="$t('operation.select')" v-model:value="searchForm.httpMethod" allow-clear>
          <a-select-option v-for="item in HttpMethodOption" :key="item.value">{{ item.text }}</a-select-option>
        </a-select>
      </SearchBarItem>
      <SearchBarItem :label="$t('mockHandler.requestUri')">
        <a-input :placeholder="$t('operation.enter')" v-model:value="searchForm.requestUri" allow-clear/>
      </SearchBarItem>
      <SearchBarItem :label="$t('mockHandler.label')">
        <a-input :placeholder="$t('operation.enter')" v-model:value="searchForm.label" allow-clear/>
      </SearchBarItem>
      <SearchBarItem last>
        <a-button class="mr-6" type="primary" @click="add">
          <template #icon>
            <plus-outlined/>
          </template>
          {{ $t('operation.insert') }}
        </a-button>
        <a-button type="primary" @click="search">
          <template #icon>
            <search-outlined/>
          </template>
          {{ $t('operation.search') }}
        </a-button>
      </SearchBarItem>
    </SearchBar>
    <a-table
        :columns="columns"
        :row-key="record => record.handlerId"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
    >
      <template #headerCell="{ column }">
        <template v-for="(item, index) in columns" :key="index">
          <span v-if="column.dataIndex && column.dataIndex === item.dataIndex">
          {{ $t(column.title) }}
          </span>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'httpMethods'">
         {{record.httpMethods.join("/")}}
        </template>
        <template v-if="column.dataIndex === 'enableStatus'">
          <Space direction="vertical">
            <Switch :checkedChildren="$t('mockHandler.enable')" :unCheckedChildren="$t('mockHandler.disable')" :checked="record.enableStatus===1" @click="updateEnableStatus(record)" />
          </Space>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <a-button class="mr-4" type="primary" size="small" @click="edit(record)">{{ $t('operation.edit') }}</a-button>
          <a-popconfirm
              :title="$t('message.confirm_delete')"
              :ok-text="$t('operation.confirm')"
              :cancel-text="$t('operation.cancel')"
              placement="left"
              @confirm="deleteRow(record)"
          >
            <a-button danger size="small">{{ $t('operation.delete') }}</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
  </section>
</template>

<script lang="ts" setup>
import type {APIResult} from '@/request'
import {MockHandlerSummaryResult, HttpMethodOption, EnableStatus} from "@/store/mockHandler";
import { Switch, Space } from 'ant-design-vue';
import {useRouter} from "vue-router";

const columns = [
  {
    title: 'mockHandler.projectName',
    dataIndex: 'projectName',
  },
  {
    title: 'mockHandler.name',
    dataIndex: 'name',
  },
  {
    title: 'mockHandler.httpMethod',
    dataIndex: 'httpMethods',
  },
  {
    title: 'mockHandler.requestUri',
    dataIndex: 'requestUri',
  },
  {
    title: 'mockHandler.label',
    dataIndex: 'label',
  },
  {
    title: 'mockHandler.status',
    dataIndex: 'enableStatus',
  },
  {
    title: 'mockHandler.updateTime',
    dataIndex: 'updateTime',
  },
  {
    title: 'table.action',
    dataIndex: 'action',
    width: '150px',
  }
]
const searchForm = reactive({
  projectId: void 0,
  name: void 0,
  httpMethod: void 0,
  requestUri: void 0,
  label: void 0,
})

const queryData = (params: Record<string, any>): Promise<{ data: APIResult<MockHandlerSummaryResult[]> }> => {
  return request.post('/api/dynamic-mock/mock/handler/query', {...params})
}

const {data: dataSource, run, loading, pagination} = usePagination(queryData, {totalKey: 'total'})

const handleTableChange = (pag: { pageSize: number; current: number; }, filters: any, sorter: any) => {
  Object.assign(searchForm, filters)
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize
  run({
    // sortField: sorter.field,
    // sortOrder: sorter.order,
    ...searchForm,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  })
}

const update = () => {
  run({
    ...searchForm,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  })
}

const search = () => {
  pagination.current = 1
  update()
}

search()

const router = useRouter();
const seeLog = ((record) => {
  const to = router.resolve({
    name: "task-log2",
    params:{taskCode:record.taskCode}
  });
  window.open(to.href, "_blank");
})

const add = () => {
  // 跳转页面
  const to = router.resolve({
    name: "mock-handler-info",
  });
  window.open(to.href, "_blank");
}

const edit = (record: MockHandlerSummaryResult) => {
  // 跳转页面
  const to = router.resolve({
    name: "mock-handler-info2",
    params:{handlerId:record.handlerId}
  });
  window.open(to.href, "_blank");
}

const updateEnableStatus= async (record:MockHandlerSummaryResult)=>{

  let  newStatus= EnableStatus.ENABLE === record.enableStatus ? EnableStatus.DISABLE : EnableStatus.ENABLE;

  const param={
    handlerId:record.handlerId,
    enableStatus:newStatus
  }

  await request.post('/api/dynamic-mock/mock/handler/enableStatus', param)

  record.enableStatus = newStatus;
}

const deleteRow = async (record: MockHandlerSummaryResult) => {

  await request.post('/api/dynamic-mock/mock/handler/del', {handlerId: record.handlerId})
  // 如果删除的是最后一页的最后一条数据,退回上一页
  const lastPage = Math.ceil(pagination.total / pagination.pageSize)
  if (pagination.current === lastPage && pagination.total % pagination.pageSize === 1) {
    pagination.current--
  }
  update()
}

const projects = ref([])
const queryProjects = async () => {
  const res = await request.post('/api/dynamic-mock/project/queryOwnAll', {})
  projects.value = res.data?.data
}
queryProjects()

</script>

<style></style>
